<template>
  <el-dialog title="设置" :visible="settingDialog" width="70%" @close="btnCancel" @open="openSetting">

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <!-- 出勤设置 -->
      <el-tab-pane label="出勤设置" name="first">
        <el-form label-position="right" label-width="100px">
          <el-form-item label="部门:">
            <el-select v-model="attendanceForm.departmentId" placeholder="请选择" @change="getAttendance">
              <el-option
                v-for="item in departs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="出勤时间:">
            <el-time-select
              v-model="attendanceForm.morningStartTime"
              :editable="false"
              style="width:160px"
              placeholder="上午上班时间"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:59'
              }"
            />-
            <el-time-select
              v-model="attendanceForm.morningEndTime"
              :editable="false"
              style="width:160px;margin-right:10px"
              placeholder="上午下班时间"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:59'
              }"
            />
            <el-time-select
              v-model="attendanceForm.afternoonStartTime"
              :editable="false"
              style="width:160px"
              placeholder="下午上班时间"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:59'
              }"
            />-
            <el-time-select
              v-model="attendanceForm.afternoonEndTime"
              :editable="false"
              style="width:160px"
              placeholder="下午下班时间"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:59'
              }"
            />
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button type="primary" @click="attendanceSave">保存更新</el-button>
          <el-button @click="btnCancel">取 消</el-button>
        </span>
      </el-tab-pane>
      <!-- 请假设置 -->
      <el-tab-pane label="请假设置" name="second">
        <el-form label-position="right" label-width="100px">
          <el-form-item label="部门:">
            <el-select v-model="leaveFormdepartmentId" placeholder="请选择" @change="getDepartsHoliday">
              <el-option
                v-for="item in departs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="假期类型:">
            <el-table
              v-if="leaveForm.length>0"
              border
              :data="leaveForm"
              style="width: 100%"
              stripe
            >
              <el-table-column
                prop="leaveType"
                label="类型"
                align="center"
                :formatter="formatFormleaveType"
              />
              <el-table-column
                label="是否可用"
                align="center"
              >
                <template #default="{row}">
                  <el-switch
                    v-model="row.isEnable"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  />
                </template>
              </el-table-column>
            </el-table>
            <!-- 如果没有  结构由枚举生成-->
            <el-table
              v-else
              border
              :data="attendancesMenu.type"
              style="width: 100%"
              stripe
            >
              <el-table-column
                prop="leaveType"
                label="类型"
                align="center"
                :formatter="formatFormleaveType"
              />
              <el-table-column
                label="是否可用"
                align="center"
              >
                <template #default="{row}">
                  <el-switch
                    v-model="row.isEnable"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button type="primary" @click="leaveSave">保存更新</el-button>
          <el-button @click="btnCancel">取 消</el-button>
        </span>
        <el-row>
          <div class="before">
            <i class="el-icon-info" />
            <span>
              事假 请假单位为0.5天 只能提交工作日内的请假单<br>
              当请假开关关闭后，员工则不可在员工端提交请假申请
            </span>
          </div>
        </el-row>
      </el-tab-pane>
      <!-- 扣款设置 -->
      <el-tab-pane label="扣款设置" name="third">
        <el-form label-position="right" label-width="100px">
          <el-form-item label="部门:">
            <el-select v-model="leaveFormdepartmentId" placeholder="请选择" @change="getDeductions">
              <el-option
                v-for="item in departs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-table ref="singleTable" :data="attendancesMenu.departmentType" style="width: 100%">
            <el-table-column>
              <template slot-scope="scope">
                <div>
                  {{ scope.row.name }}
                  <el-switch
                    v-model="scope.row.isEnable"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="handleStatus($event,scope.row)"
                  />
                </div>
                <!-- 迟到 -->
                <div v-if="scope.row.dedTypeCode==='51000'" class="attentInfo">
                  <p>
                    迟到≤
                    <el-input
                      v-model="scope.row.periodUpperLimit"
                      class="inputInfo"
                      value="30"
                      @input.native="handleInput($event)"
                    />分钟
                  </p>
                  <div class="deductionInfo">
                    <p>
                      迟到≤
                      <el-input
                        v-model="scope.row.timesUpperLimit"
                        class="inputInfo"
                        @input.native="handleInput($event)"
                      />次，每次扣款
                      <el-input
                        v-model="scope.row.dedAmonutUpperLimit"
                        class="inputInfo"
                        @input.native="handleInput($event)"
                      />元
                    </p>
                    <p>
                      迟到>
                      <el-input
                        v-model="scope.row.timesLowerLimit"
                        class="inputInfo"
                        disabled
                        @input.native="handleInput($event)"
                      />次，每次扣款
                      <el-input
                        v-model="scope.row.dedAmonutLowerLimit"
                        class="inputInfo"
                        @input.native="handleInput($event)"
                      />元
                    </p>
                  </div>
                  <p>
                    迟到>
                    <el-input v-model="scope.row.periodLowerLimit" class="inputInfo" disabled />分钟
                  </p>
                  <div class="deductionInfo">
                    <p>
                      迟到>
                      <el-input
                        v-model="scope.row.absenceTimesUpperLimt"
                        class="inputInfo"
                        disabled
                      />次，每次旷工
                      <el-input
                        v-model="scope.row.absenceDays"
                        class="inputInfo"
                        @input.native="handleInputPoint($event)"
                      />天
                    </p>
                  </div>
                </div>
                <!-- 早退 -->
                <div v-if="scope.row.dedTypeCode==='52000'" class="attentInfo">
                  <p>
                    早退≤
                    <el-input
                      v-model="scope.row.periodUpperLimit"
                      class="inputInfo"
                      value="30"
                      @input.native="handleInput($event)"
                    />分钟
                  </p>
                  <div class="deductionInfo">
                    <p>
                      早退≤
                      <el-input
                        v-model="scope.row.timesUpperLimit"
                        class="inputInfo"
                        @input.native="handleInput($event)"
                      />次，每次扣款
                      <el-input
                        v-model="scope.row.dedAmonutUpperLimit"
                        class="inputInfo"
                        @input.native="handleInput($event)"
                      />元
                    </p>
                    <p>
                      早退>
                      <el-input v-model="scope.row.timesLowerLimit" class="inputInfo" disabled />次，每次扣款
                      <el-input
                        v-model="scope.row.dedAmonutLowerLimit"
                        class="inputInfo"
                        @input.native="handleInput($event)"
                      />元
                    </p>
                  </div>
                  <p>
                    早退>
                    <el-input v-model="scope.row.periodLowerLimit" class="inputInfo" disabled />分钟
                  </p>
                  <div style="padding-left:120px;">
                    <p>
                      早退>
                      <el-input
                        v-model="scope.row.absenceTimesUpperLimt"
                        class="inputInfo"
                        disabled
                      />次，每次旷工
                      <el-input
                        v-model="scope.row.absenceDays"
                        class="inputInfo"
                        @input.native="handleInputPoint($event)"
                      />天
                    </p>
                  </div>
                </div>
                <!-- 旷工 -->
                <div v-if="scope.row.dedTypeCode==='53000'" class="attentInfo">
                  <p>
                    旷工按
                    <el-input
                      v-model="scope.row.fineSalaryMultiples"
                      class="inputInfo"
                      @input.native="handleInput($event)"
                    />倍工资处罚
                  </p>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <span class="dialog-footer">
            <el-button type="primary" @click="deductionsSave">保存更新</el-button>
            <el-button @click="btnCancel">取 消</el-button>
          </span>
        </el-form>
      </el-tab-pane>
      <!-- 加班设置 -->
      <el-tab-pane label="加班设置" name="fourth">
        <el-form
          ref="overtimeForm"
          :model="overtimeBase"
          label-width="110px"
        >

          <el-form-item label="部门：" prop="departmentId">
            <el-select
              v-model="overtimeBase.departmentId"
              placeholder="请选择"
              @change="getOvertime"
            >
              <el-option
                v-for="item in departs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="加班规则：">
            <div v-for="item in overtimeBase.rules" :key="item.id" class="ruleInfo">
              <el-row>
                <el-col :span="8">
                  <div class="grid-content bg-purple">
                    <el-switch v-model="item.isEnable" />
                    &nbsp;&nbsp;{{ item.rule }}
                  </div>
                </el-col>
                <el-col :span="16">
                  <div class="grid-content bg-purple-light">
                    <span class="pad">
                      <el-checkbox v-model="item.isTimeOff">调休假</el-checkbox>
                    </span>
                    <template>
                      <el-time-select
                        v-model="item.ruleStartTime"
                        class="clooseTime"
                        :picker-options="{
                          start: '01:00',
                          step: '00:15',
                          end: '23:59'
                        }"
                        style="width:100px;"
                        :disabled="item.isTimeOff===false"
                      />
                      <el-time-select
                        v-model="item.ruleEndTime"
                        :picker-options="{
                          start: '01:00',
                          step: '00:15',
                          end: '23:59',
                          minTime: item.startTime
                        }"
                        style="width:100px;"
                        :disabled="item.isTimeOff===false"
                      />
                    </template>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
          <el-form-item label="打卡验证：" prop="isClock">
            <el-switch v-model="overtimeBase.isClock" />&nbsp;&nbsp;加班需要有打卡记录
          </el-form-item>
          <el-form-item label="开启补偿：" prop="isCompensationint">
            <el-switch v-model="overtimeBase.isCompensationint" />
          </el-form-item>
          <el-form-item label="调休假设置：" prop="latestEffectDate">
            <div class="ruleInfo">
              最晚有效期： 次年
              <el-date-picker
                v-model="overtimeBase.latestEffectDate"
                type="date"
                placeholder="选择日期"
                style="width:150px;"
              />
            </div>
          </el-form-item>
          <el-form-item label prop="unit">
            <div class="ruleInfo">
              <p>
                请假最小单位
                <el-input v-model="overtimeBase.unit" style="width:50px" />天
              </p>
            </div>
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button type="primary" @click="overtimeSave">保存更新</el-button>
          <el-button @click="btnCancel">取 消</el-button>
        </span>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import { getDepartments } from '@/api/departments'
import { getAttendance, attendanceSave, getLeave, leaveSave, getDeductions, deductionsSave, getOvertime, overtimeSave } from '@/api/attendances'
import attendancesMenu from '@/api/constant/attendance'
export default {
  props: {
    settingDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeName: 'first',
      departs: [],
      attendanceForm: { // 出勤设置表单对象
        departmentId: '',
        morningStartTime: '',
        morningEndTime: '',
        afternoonStartTime: '',
        afternoonEndTime: ''
      },
      leaveForm: [], // 请假设置 部门对应请假类型
      leaveFormdepartmentId: '',
      attendancesMenu,
      overtimeBase: {
        departmentId: '',
        isClock: false,
        isCompensationint: false,
        latestEffectDate: '',
        unit: '',
        rules: attendancesMenu.overtimeType
      }

    }
  },
  async created() {
    this.departs = (await getDepartments()).depts
    // console.log(this.departs)
  },
  methods: {
    // 标签页切换 自动发送请求 总裁办部门数据
    handleClick(tab, event) {
      // console.log(tab, event)
      if (tab.label === '请假设置') {
        this.leaveFormdepartmentId = this.departs[0].id
        this.getDepartsHoliday(this.departs[0].id)
      } else if (tab.label === '出勤设置') {
        this.attendanceForm.departmentId = this.departs[0].id
        this.getAttendance(this.attendanceForm.departmentId)
      } else if (tab.label === '扣款设置') {
        this.attendancesMenu.departmentType.departmentId = this.departs[0].id
        this.getDeductions(this.departs[0].id)
      } else if (tab.label === '加班设置') {
        this.overtimeBase.departmentId = this.departs[0].id
        this.getOvertime(this.overtimeBase.departmentId)
      }
    },
    btnCancel() {
      this.$emit('update:settingDialog', false)
    },
    // 默认每次弹出设置弹出框 定位到出勤设置 并展示部门的出勤时间
    openSetting() {
      this.activeName = 'first'
      this.attendanceForm.departmentId = this.departs[0].id
      this.getAttendance(this.attendanceForm.departmentId)
    },
    // 根据部门查询出勤时间
    async getAttendance(departmentId) {
      // console.log(departmentId)
      this.attendanceForm = await getAttendance('departmentId=' + departmentId)
      // console.log(this.attendanceForm)
    },
    // 保存考勤设置
    async attendanceSave() {
      await attendanceSave(this.attendanceForm)
      this.$message.success('保存成功')
      this.btnCancel()
    },
    // 根据部门查询请假规则设置
    async getDepartsHoliday(departmentId) {
      // console.log(departmentId)
      const res = await getLeave('departmentId=' + departmentId)
      this.leaveForm = res.map(item => {
        if (item.isEnable === 1) {
          item.isEnable = true
        } else {
          item.isEnable = false
        }
        return item
      })
    },
    // 数据改造
    formatFormleaveType(row, column, cellValue) {
      const obj = attendancesMenu.type.find(item => item.leaveType === cellValue)
      return obj ? obj.name : '未知'
    },
    // 保存请假设置
    async leaveSave() {
      let data = null
      if (this.leaveForm.length > 0) { // 如果之前就有数据 直接用之前的数据用户修改后 发请求
        // console.log(this.leaveForm)
        data = this.leaveForm.map(item => {
          if (item.isEnable) {
            item.isEnable = 1
          } else {
            item.isEnable = 0
          }
          return item
        })
      } else { // 如果之前没有数据 生成数据 用户修改后发送请求
        data = this.attendancesMenu.type.map(item => {
          item.departmentId = this.leaveFormdepartmentId // 添加部门id
          if (item.isEnable) { // 修改isEnable 为数字1 0
            item.isEnable = 1
          } else {
            item.isEnable = 0
          }
          return item
        })
        // console.log(data)
      }
      await leaveSave(data)
      this.$message.success('保存更新成功')
      this.btnCancel()
    },
    // 根据部门查询考勤扣款规则
    async getDeductions(departmentId) {
      const res = await getDeductions('departmentId=' + departmentId)
      // console.log(res, this.attendancesMenu.departmentType)
      const data = this.attendancesMenu.departmentType.map((item, i) => {
        if (res.length > 0) {
          item = { ...item, ...res[i] }
        }
        return item
      })
      this.attendancesMenu.departmentType = data.map(item => {
        if (item.isEnable === 1) {
          item.isEnable = true
        } else {
          item.isEnable = false
        }
        return item
      })
      // console.log(this.attendancesMenu.departmentType)
    },
    // 保存考勤扣款规则
    async deductionsSave() {
      const data = this.attendancesMenu.departmentType.map(item => {
        if (item.isEnable) {
          item.isEnable = 1
        } else {
          item.isEnable = 0
        }
        return item
      })
      await deductionsSave(data)
      this.$message.success('保存更新成功')
      this.btnCancel()
    },
    // 根据部门查询考勤加班规则
    async getOvertime(departmentId) {
      this.overtimeBase = {
        departmentId: '',
        isClock: false,
        isCompensationint: false,
        latestEffectDate: '',
        unit: '',
        rules: attendancesMenu.overtimeType
      }
      const res = await getOvertime('departmentId=' + departmentId)
      const data = { ...this.overtimeBase, ...res.dayOffConfigs, ...res.extraDutyConfig }
      if (data.isClock === 1 || data.isCompensationint === '1') {
        data.isClock = true
        data.isCompensationint = true
      } else {
        data.isClock = false
        data.isCompensationint = false
      }

      this.overtimeBase = data
    },
    // 加班配置保存
    async overtimeSave() {
      if (this.overtimeBase.isClock || this.overtimeBase.isCompensationint) {
        this.overtimeBase.isClock = '1'
        this.overtimeBase.isCompensationint = '1'
      } else {
        this.overtimeBase.isClock = '0'
        this.overtimeBase.isCompensationint = '0'
      }
      await overtimeSave(this.overtimeBase)
      this.$message.success('保存更新成功')
      this.btnCancel()
    }
  }
}
</script>

<style lang="scss" scoped>
.departs{
  margin-bottom: 10px;
}
.dialog-footer{
  padding-top: 10px;
  display: flex;
  justify-content: center;
}
.inputInfo{width: 50px;}

.attentInfo {
  p {
    padding: 3px 0;
    margin: 0;
  }
  .el-input--medium {
    .el-input__inner {
      height: 24px;
      line-height: 24px;
    }
  }
}
.deductionInfo{
  padding-left: 120px;
}
.titmInfo {
  .el-date-editor--timerange.el-input__inner {
    width: 280px;
  }
  .el-date-editor .el-range-separator {
    padding: 0 15px 0 0;
  }
}
.ruleInfo {
  .el-input--medium .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
}
.tipInfo {
  p {
    padding: 5px 0;
  }
}
.titInfo {
  border-bottom: 1px solid #dcdfe6;
  height: 30px;
  line-height: 30px;
  padding: 0 0 15px;
}
.attentInfo {
  padding: 20px 15px 0px 80px;
}
.ruleInfo {
  .pad {
    padding-left: 80px;
  }
}
.before {
  margin-top: 10px;
  line-height: 34px;
  width: 100%;
  background-color: #fdf6ec;
  display: flex;
  justify-content: flex-start;
  padding: 0px 10px;
  border-radius: 3px;
  color: #e6a23c;
  i {
    padding-top: 15px;
    margin-right: 5px;
    color: #e6a23c;
    font-size: 40px;
  }
}
.clooseTime{
  margin: 10px;
}
</style>
